'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

 

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 

Constraints:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

'''

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        
        #有点不太熟悉，多刷几遍
        
        min = nums[0]+nums[1]+nums[2]
        #数组排序
        nums.sort()
        
        
        for i in range(0,len(nums)-1):
            if i>0 and nums[i]==nums[i-1]:
                i +=1
                continue
            
            l = i+1
            r = len(nums)-1
            while(l<r):
                sum = nums[i]+nums[l]+nums[r]
                
                if abs(sum-target) < abs(min-target):
                      min = sum
                if sum >target:
                    r -=1
                elif sum ==target:
                    return sum
                else:
                    l +=1
        return min
        
        
        
#         # 0  1 2 3   len=4        
#         #-3 0 1 2 
#         for i in range(0,len(nums)):
#             #找到靠近目标的元素
#             if target==nums[i] or target<nums[i]:
                
                
#                 if (i+1) < len(nums) and (i-1)>-1:
#                         return nums[i-1]+nums[i]+nums[i+1]
#                 elif (i+1) < len(nums) and (i-1)==-1:
#                         return nums[i]+nums[i+1]+nums[i+2]
#                 elif (i+1) > len(nums) and (i-1)>-1:
#                         return nums[len(nums)-1]+nums[len(nums)-2]+nums[len(nums)-3]
#             else:
#                 return nums[len(nums)-1]+nums[len(nums)-2]+nums[len(nums)-3]
                 
            